const screenWidth = window.innerWidth
const screenHeight = window.innerHeight

import Sprite from './sprite'
import global from './global'


/**
 * 敌机
 */
export default class Enemy extends Sprite{

  constructor() {
    super('images/enemy.png', 60, 60)
    this.x = Math.ceil(Math.random() * screenWidth) - this.width 
    if(this.x < 0){
      this.x = 0
    }
  }

  init(speed = 10) {
    this.speed = speed
    this.visible = true
  }

  update() {
    this.y = this.y + this.speed
    if (this.y > screenHeight) {
      this.visible = false
      global.removeEnmey(this)
    }
  }

  render(ctx) {
    // 是否播放动画
    if (this.isPlayAnimation){
      if (this.animationImgOffset < this.animationImgs.length - 1){
        let img = this.animationImgs[this.animationImgOffset]
        ctx.drawImage(
          img, this.x, this.y, 64, 48
        )
      }else{
        this.isPlayAnimation  = false
      }
      this.animationImgOffset ++
    }
    if (!this.visible) {
      return
    }
    ctx.drawImage(
      this.img, this.x, this.y, this.width, this.height
    )
  }

  // 播放动画
  playAnimation() {
    this.visible = false
    let animationImgs = []
    for (var i = 0; i < 19 ; i++){
      let img = new Image()
      img.src = 'images/explosion' + (i + 1) +  '.png'
      animationImgs.push(img)
    }
    this.animationImgs = animationImgs
    this.animationImgOffset = 0
    this.isPlayAnimation = true
  }
}
